package com.zhx.sweet.session;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhanghaixuan
 * @create 2017/11/26-下午10:16
 **/
public class AbstractSessionStrategy {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 跳转前是否创建新的session
     */
    private boolean createNewSession = true;

    private ObjectMapper objectMapper = new ObjectMapper();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    /**

     */
    public AbstractSessionStrategy() {

    }


    protected void onSessionInvalid(HttpServletRequest request, HttpServletResponse response) throws IOException {

        if (createNewSession) {
            request.getSession();
        }

        String sourceUrl = request.getRequestURI();

        logger.info("引发跳转的url是"+sourceUrl);

        String contextPath = request.getContextPath();

        if(contextPath.equals(sourceUrl) || sourceUrl.equals(contextPath+"/")){
            //首页跳转问题  直接重定向到  根目录下
            redirectStrategy.sendRedirect(request,response,sourceUrl);
        }

        Object result = buildResponseContent(request);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }

    /**
     * @param request
     * @return
     */
    protected String buildResponseContent(HttpServletRequest request) {
        String message = "身份失效,请重新登录!";
        if(isConcurrency()){
            message = message + "，有可能是并发登录导致的";
        }
        return  message;
    }

    /**
     * session失效是否是并发导致的
     * @return
     */
    protected boolean isConcurrency() {
        return false;
    }


    public void setCreateNewSession(boolean createNewSession) {
        this.createNewSession = createNewSession;
    }
}
